package xyz.wjwnya.auth_module.controller;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import xyz.wjwnya.auth_module.dto.LoginRequest;
import xyz.wjwnya.auth_module.service.AuthService;
import xyz.wjwnya.auth_module.vo.UserTypeInfo;
import xyz.wjwnya.common.auth.UserSessionData;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/auth")
public class AuthController {

    private final AuthService authService;

    public AuthController(AuthService authService) {
        this.authService = authService;
    }

    @PutMapping("/login")
    public void login(@RequestBody @Validated LoginRequest loginRequest, HttpServletRequest request) {
        AuthService.UserData userData = authService.login(
            loginRequest.getAccount(), loginRequest.getPassword(), loginRequest.getUserType()
        );
        request.getSession().setAttribute(UserSessionData.SESSION_DATA_KEY, new UserSessionData(
            userData.getAccount(),
            userData.getUsername(),
            userData.getUserType()
        ));
    }

    @PostMapping("/logout")
    public void logout(HttpSession session, SessionStatus sessionStatus) {
        session.invalidate();
        sessionStatus.setComplete();
    }

    @GetMapping("/user_type/all")
    public List<UserTypeInfo> getAllUserType() {
        return authService.getAllUserType().stream().map(userTypeData -> new UserTypeInfo(
                userTypeData.getName(), userTypeData.getFormat()
        )).collect(Collectors.toList());
    }

}
